﻿#region Using

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;

using Gizmox.WebGUI.Common;
using Gizmox.WebGUI.Forms;
using Gizmox.WebGUI.Common.Resources;
using System.IO;
using System.Configuration;

#endregion

namespace VisualWebGuiApplication2
{
    public partial class TabkFix : UserControl
    {
        int lastid = 0;
      /*  BindingSource _bsTankOpen;
        GazOnDevEntities db2 = new GazOnDevEntities();*/
         private ItemPanel Listview1;
         Tank_Stocks tanktofix;
         BindingList<TankFixOperation> lst = new BindingList<TankFixOperation>();
         BindingSource bs;
         private Gizmox.WebGUI.Forms.ListView LVAutoGen;
         private Gizmox.WebGUI.Forms.ListView LVManualGen;
         private Gizmox.WebGUI.Forms.ColumnHeader columnHeader1;
         private Gizmox.WebGUI.Forms.ColumnHeader columnHeader2;
         private Gizmox.WebGUI.Forms.ColumnHeader columnHeader3;
        public TabkFix()
        {
            InitializeComponent();
         
           
            this.RightToLeft = Gizmox.WebGUI.Forms.RightToLeft.Yes;


            textBox1.Leave += new EventHandler(textBox1_Leave);
           openFileDialog1.FileOk+=new CancelEventHandler(openFileDialog1_FileOk);
        }

        public TabkFix(string tankid)
        {
            InitializeComponent();


            this.RightToLeft = Gizmox.WebGUI.Forms.RightToLeft.Yes;


            textBox1.Leave += new EventHandler(textBox1_Leave);
            textBox1.Text = tankid;
            txtcreatedby.Text = string.Format("{0}", Session["username"]);
            EventArgs ev = new EventArgs();
            textBox1_Leave(textBox1, ev);

            openFileDialog1.FileOk += new CancelEventHandler(openFileDialog1_FileOk);
        }


       


        void textBox1_Leave(object sender, EventArgs e)
        {
           // get details of the gaz tank 
            btnFinishFix.Enabled = true;
            btnOpenTank.Enabled = true;
            bool error = false;
            using (GazOnDevEntities db=new GazOnDevEntities())
            {

                if(!string.IsNullOrEmpty(textBox1.Text))
                {

                    tanktofix = db.Tank_Stocks.FirstOrDefault(x => (x.TankNumber == textBox1.Text) && ((x.TankSystemStatus == "2") || (x.TankSystemStatus == "3") || (x.TankSystemStatus == "1") || (x.TankSystemStatus == "4") || (x.TankSystemStatus == "5")));
                    if (null == tanktofix)
                    {
                        MessageBox.Show("לא קיים מספר צובר כזה שהקלט לשיפוץ");
                        return;
                    
                    }
                  if (tanktofix.Id < 1)
                  {
                      error = true;
                  }
                }else
                {
                    error = false;
                  
                
                }

                if (error)
                {
                    MessageBox.Show("לא קיים מספר צובר כזה שהקלט לשיפוץ");
                }
                else
                {
                    if ((tanktofix.TankSystemStatus == "1") || (tanktofix.TankSystemStatus == "4") || (tanktofix.TankSystemStatus == "5"))
                    {
                        if (tanktofix.TankSystemStatus == "4")
                        { 
                         MessageBox.Show("אתה צופה בצובר שיצא מהמלאי נא לא  לערוך ");
                        }
                        if (tanktofix.TankSystemStatus == "5")
                         {
                                MessageBox.Show(" אתה צופה בצובר פסול ");
                         }
                        if (tanktofix.TankSystemStatus == "6")
                        {
                            MessageBox.Show(" אתה צופה בצובר מושמד ");
                        }
                        if (tanktofix.TankSystemStatus == "1")
                        {
                            MessageBox.Show("אתה צופה בצובר במלאי  נא לא  לערוך ");
                        }
                           
                       
                        btnFinishFix.Enabled = false;
                        btnOpenTank.Enabled = false;

                    }
                    else
                    {
                        btnFinishFix.Enabled = true;
                        btnOpenTank.Enabled = true;
                    }
                    flowLayoutPanel1.Controls.Clear();
                    txt_Tank_Size.Text = tanktofix.Tank_Size.ToString();
                    txt_Tank_Size.Enabled = false;
                    txtmanufacture_name.Text = tanktofix.manufacture_name;
                    txtmanufacture_name.Enabled = false;
                    txtYear_of_manufacture.Text= tanktofix.Year_of_manufacture.ToString();
                    txtYear_of_manufacture.Enabled = false;
                    textBox2.Text = tanktofix.TankFixNumber;
                    comboBox1.SelectedIndex =Convert.ToInt32(tanktofix.tankStatus);
                    if (string.IsNullOrEmpty(tanktofix.cteatedby))
                    {
                        txtcreatedby.Text = string.Format("{0}", Session["username"]);
                    }
                    else
                    {
                        txtcreatedby.Text = tanktofix.cteatedby;
                    }
                    txtDate1.Text = tanktofix.Datetime;
                    txtorderingName.Text = tanktofix.GazCompanyName;
                    comboBox1.Enabled = false;
                    FillListView(tanktofix.Id);
                    FillUploadLinks(tanktofix.Id);
                    
                }



                
            }
        }
        private void FillUploadLinks(int tankfixid)
        {



            string idoftank = tankfixid.ToString();
            // ad values to database  
            using (GazOnDevEntities db = new GazOnDevEntities())
            {
                var query = from a in db.UploadedFilesOftanks
                            where a.tankfixid == idoftank 
                            select a;
                if(null != query)
                {

              
              List<UploadedFilesOftank> allfiles=   query.ToList<UploadedFilesOftank>();
              foreach (var item in allfiles)
              {

                  LinkLabel linkLabel1 = new LinkLabel();
                  linkLabel1.Text = item.filename;
                  linkLabel1.Url = item.filepath;
                  flowLayoutPanel1.Controls.Add(linkLabel1);
              }
            }
                
               
            }
        
        }
            // Fill up ListView
        private void FillListView(int tankid)
        {
            // 
            // Listview1
            // 
            this.Listview1 = new ItemPanel(tankid);
            this.Listview1.AutoValidate = Gizmox.WebGUI.Forms.AutoValidate.EnablePreventFocusChange;
            this.Listview1.Dock = Gizmox.WebGUI.Forms.DockStyle.Fill;
            this.Listview1.DockPadding.All = 3;
            this.Listview1.Location = new System.Drawing.Point(0, 0);
            this.Listview1.Name = "Listview1";
            this.Listview1.Padding = new Gizmox.WebGUI.Forms.Padding(3);
            this.Listview1.Size = new System.Drawing.Size(702, 256);
            this.Listview1.TabIndex = 0;
            this.Listview1.Text = "ItemPanel";
            this.panel2.Controls.Clear();
            this.panel2.Controls.Add(this.Listview1);
          //  this.panel2.Controls.Add(this.Listview1);
        }
   
        private void  ListviewDatabinf()
        {
        
     
        
        }
     

    
        private void btnOpenTank_Click(object sender, EventArgs e)
        {
          
           

            using (GazOnDevEntities db = new GazOnDevEntities())
            {
                TankFixOperation newtankfixoperationrecord = new TankFixOperation();


                newtankfixoperationrecord.tankID = tanktofix.Id;
               
                 db.TankFixOperations.Where(x=>x.tankID == tanktofix.Id ).ToList().ForEach(db.TankFixOperations.DeleteObject);
                 db.SaveChanges();
                List<TankFixOperation> _opList = new List<TankFixOperation>();
                foreach (ListViewItem item in Listview1.mobjListView.Items)
	                {
                        TankFixOperation row = new TankFixOperation();
                        row.tankID = tanktofix.Id;
                    //ITERATE THROUGHT listview and save values to database tankFixoperation
                        if (!string.IsNullOrEmpty(item.SubItems[1].ToString()))
                        {
                            row.amount = Convert.ToInt32(item.SubItems[1].ToString());
                        }
                        if (!string.IsNullOrEmpty(item.SubItems[0].ToString()))
                        {
                            row.title = item.SubItems[0].ToString();
                        }
                        if (!string.IsNullOrEmpty(item.SubItems[2].ToString()))
                        {
                            row.date = Convert.ToDateTime(item.SubItems[2].ToString());
                        }
                        else
                        {
                            row.date = null;
                        }
                        if (!string.IsNullOrEmpty(item.SubItems[3].ToString()))
                        {
                            row.note = item.SubItems[3].ToString();
                        }

                        _opList.Add(row);
                        db.AddToTankFixOperations(row);
                  //      MessageBox.Show("Title" + item.SubItems[0].ToString());
		 
	                }


                tanktofix.cteatedby = txtcreatedby.Text;
                // הסתיים שיפוץ אזי יופיע במלאי
                tanktofix.TankSystemStatus = "3";
                tanktofix.TankFixNumber = textBox2.Text;
                db.Tank_Stocks.Attach(tanktofix);
                db.ObjectStateManager.ChangeObjectState(tanktofix, EntityState.Modified);
                 // db.Tank_Stocks.FirstOrDefault(x => x.TankNumber == textBox1.Text)
                //Tank_Stocks newrecord = new Tank_Stocks();
                //newrecord.TankNumber = txtorderingName.Text;
                //newrecord.type = comboBox1.SelectedIndex.ToString();
                //newrecord.Datetime = dateTimePicker1.Value;
            //this is a status of fixing progress
                
               // newrecord.TankSystemStatus = "3";
            
                if (db.SaveChanges() > 0)
                {
                    MessageBox.Show("פעולת ההוספה הצליחה");
                 //   btnOpenTank.Enabled = false;
                    
                }
                else
                {
                   
                }
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            textBox1_Leave(sender, e);
        }

        private void btnupload_Click(object sender, EventArgs e)
        {
                              // Invoke Dialog.
            openFileDialog1.ShowDialog();
            // save files to database 
        }
 
private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
{
    OpenFileDialog objOFD = sender as OpenFileDialog;
    if (sender == null || objOFD.Files == null || objOFD.Files.Count == 0)
    {
        return;
    }
 
    Gizmox.WebGUI.Common.Resources.FileHandle objFile = null;
    if (objOFD.Files[0] == null || !(objOFD.Files[0] is Gizmox.WebGUI.Common.Resources.FileHandle))
    {
        return;
    }
   
 
    // Display original file name, of the first uploaded file, on a label.

    string newguid = Guid.NewGuid().ToString();
    string path = ConfigurationManager.AppSettings["uploadfilepath"].ToString() +newguid;

    DirectoryInfo objDirectoryInfo = Directory.CreateDirectory(path);

    for (int intIndex = 0; intIndex < objOFD.Files.Count; intIndex++)
    {
        objOFD.Files[intIndex].SaveAs(Path.Combine(objDirectoryInfo.FullName,
                                                   ((Gizmox.WebGUI.Common.Resources.HttpPostedFileHandle)(objOFD.Files[intIndex])).PostedFileName));
        objFile = objOFD.Files[intIndex] as Gizmox.WebGUI.Common.Resources.FileHandle;
        LinkLabel linkLabel1 = new LinkLabel();
        linkLabel1.Text = objFile.OriginalFileName;
        linkLabel1.Url = "files/" + newguid + "/" + objFile.OriginalFileName;

        flowLayoutPanel1.Controls.Add(linkLabel1);

        // ad values to database  
        using (GazOnDevEntities db = new GazOnDevEntities())
        {
            UploadedFilesOftank newfile = new UploadedFilesOftank();
            newfile.filename = objFile.OriginalFileName;
            newfile.filepath = "files/" + newguid + "/" + objFile.OriginalFileName;
            newfile.tankfixid = tanktofix.Id.ToString();

            db.AddToUploadedFilesOftanks(newfile);
            db.SaveChanges();
        }
    }


        }

        private void btnReportPrint_Click(object sender, EventArgs e)
        {
           /* foreach (Control item in this.Controls)
            {
                item.Enabled = false;
                //if(item.)

            }
            */
          //  btnOpenTank.Enabled = false;
            frmReportTankRecipet tanko = new frmReportTankRecipet(tanktofix.Id, "report2");
            tanko.ShowDialog();
        }

        private void btnFinishFix_Click(object sender, EventArgs e)
        {
            if(tanktofix.Id >0)
            {
                using (GazOnDevEntities db=new GazOnDevEntities())
                {
                    tanktofix.TankSystemStatus = "1";

                    db.Tank_Stocks.Attach(tanktofix);
                    db.ObjectStateManager.ChangeObjectState(tanktofix, EntityState.Modified);
                   

                    // newrecord.TankSystemStatus = "3";

                    if (db.SaveChanges() > 0)
                    {
                        MessageBox.Show("פעולת סיום שיפוץ הצליחה ");
                        //   btnOpenTank.Enabled = false;

                    }
                    
                }

            }else
            {
                MessageBox.Show("נא לבחור צובר");
            }
        }

        private void btnReportPrint_Click_1(object sender, EventArgs e)
        {
            frmReportTankRecipet tanko = new frmReportTankRecipet(tanktofix.Id, "report2");
            tanko.ShowDialog();
        }

        private void buttnDestroyTank_Click(object sender, EventArgs e)
        {
            if (tanktofix.Id > 0)
            {
                using (GazOnDevEntities db = new GazOnDevEntities())
                {
                    tanktofix.TankSystemStatus = "5";

                    db.Tank_Stocks.Attach(tanktofix);
                    db.ObjectStateManager.ChangeObjectState(tanktofix, EntityState.Modified);


                    // newrecord.TankSystemStatus = "3";

                    if (db.SaveChanges() > 0)
                    {
                        MessageBox.Show("פעולת פסילת צובר הצליחה ");
                        //   btnOpenTank.Enabled = false;

                    }

                }

            }
            else
            {
                MessageBox.Show("נא לבחור צובר");
            }

        }

        private void button1_Click_1(object sender, EventArgs e)
        {
            if (tanktofix.Id > 0)
            {
                using (GazOnDevEntities db = new GazOnDevEntities())
                {
                    tanktofix.TankSystemStatus = "6";

                    db.Tank_Stocks.Attach(tanktofix);
                    db.ObjectStateManager.ChangeObjectState(tanktofix, EntityState.Modified);


                    // newrecord.TankSystemStatus = "6";

                    if (db.SaveChanges() > 0)
                    {
                        MessageBox.Show("פעולת השמדת צובר הצליחה ");
                        //   btnOpenTank.Enabled = false;

                    }

                }

            }
            else
            {
                MessageBox.Show("נא לבחור צובר");
            }

        }
    }
}